package com.pitop.interceptor;

import com.alibaba.fastjson.JSON;
import com.pitop.core.entity.BeanRet;
import com.pitop.t.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
		
		Subject subject = SecurityUtils.getSubject();
		
		User user = (User) subject.getPrincipal();
		
		if (user != null) {
			return true;
		}

		//未登录需要跳转的地址
		String loginUri = "/page/login";
		//如果是ajax请求响应头会有，x-requested-with
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Location", loginUri);    //跳转登陆页面
		response.setHeader("serverError", "sessionOut");  //session过期
		response.getWriter().write(JSON.toJSONString(BeanRet.create(false, "登陆已失效，请重新登陆！")));
		return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {
		
	}

}
